function getScroll(){
    // height
    let scrollHeight, bodyScrollHeight = 0, documentScrollHeight = 0;
    if(document.body){
        bodyScrollHeight = document.body.scrollHeight
    }
    if(document.documentElement){
        documentScrollHeight = document.documentElement.scrollHeight
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight

    return {
        left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
        top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
        height: scrollHeight,
    }
}
Element.prototype.hide = function () {
    this.style.display = 'none'
}
Element.prototype.show = function (display = 'block') {
    this.style.display = display
}
Element.prototype.toggleShow = function (display = 'block') {
    if (this.style.display === display) {
        this.hide()
        return false
    } else {
        this.style.display = display
        return true
    }
}
Element.prototype.showLoading = function () {
    if(!this.querySelector('.loading')) {
        let loadingDom = document.createElement('div')
        loadingDom.className = 'loading'
        let iconDom = document.createElement('i')
        iconDom.className = 'iconfont icongengxin'
        loadingDom.appendChild(iconDom)
        if(this.tagName === 'BODY') {
            // 获取滚动条高度
            loadingDom.style.top = getScroll().top + 'px'
            this.style.overflow = 'hidden'
            loadingDom.style.zIndex = '999'
        } else {
            loadingDom.style.zIndex = (+this.style.zIndex + 1) + ''
            if(this.scrollTop === 0) {
                loadingDom.style.top = '-1px'
                loadingDom.style.height = 'calc(100% + 2px)'
             } else  {
                loadingDom.style.top = this.scrollTop + 'px'
                loadingDom.style.height = 'calc(100% + 1px)'
            }
        }

        this.appendChild(loadingDom)
    }
}
Element.prototype.hideLoading = function () {
    let e = this.querySelector('.loading')
    if(e) {
        e.remove()
        if(this.tagName === 'BODY') {
            this.style.overflow = ''
        }
    }
}

function showLoading (el= document.body) {
    if(el) {
        el.showLoading()
    }
}
function hideLoading(el = document.body) {
    el.hideLoading()
}
function showToast(val, time = 1500) {
    let toastDom = document.createElement('div')
    toastDom.innerHTML = val
    toastDom.className = 'toast'
    if(val.length < 40) {
        toastDom.style.whiteSpace = 'nowrap'
    }
    toastDom.style.top = getScroll().top + 200 + 'px'
    document.body.appendChild(toastDom)
    setTimeout(() => {
        document.querySelector('.toast').remove()
    }, 1500)
}
function showMask({zIndex,event} = {}) {
    if(document.querySelector('body>.mask')) {
        return
    }
    let mask = document.createElement('div')
    mask.className = 'mask'
    if(zIndex) {
        mask.style.zIndex = zIndex
    }
    mask.style.top = getScroll().top  + 'px'
    document.body.appendChild(mask)
    mask.show()
    if(event) {
        mask.addEventListener('click', () => {
            event()
            hideMask()
        })
    } else {
        mask.addEventListener('click', hideMask)
    }
    if(gugeeGobal.isMobile) {
        lockScroll()
    } else {
        document.body.style.overflowY = 'hidden'
    }
}
function hideMask() {
    let e = document.querySelector('body>.mask')
    if(e) {
        e.hide()
        e.remove()
        if(gugeeGobal.isMobile) {
            unlockScroll()
        } else {
            document.body.removeAttribute('style')
        }
    }
}
function unlockScroll () {
    const scrollY = +document.body.style.top.replace('px', '')
    // document.body.style.position = undefined
    // document.body.style.top = undefined
    // document.body.style.left = undefined
    // document.body.style.right = undefined
    document.body.removeAttribute('style')
    window.scrollTo(0, parseInt(scrollY || 0 ) * -1)
}

function lockScroll () {
    document.body.style.top = `-${window.scrollY}px`;
    document.body.style.position = 'fixed';
    document.body.style.left = '0';
    document.body.style.right = '0';
}
// type : 0:single 1:both
function showModal(config) {
    if(!config.type){
        closeModal()
    }
    const defaultConfig = {
        class: '',
        content: 'body',
        showHeader: true,
        position: {
            top: 200
        },
        mode: 0, // 0:default 1:内容弹窗模式
        title: '',
        isShowConfirmBtn: true,
        confirmBtnText: 'Confirm',
        confirmBtn: {
            event: closeModal
        },
        isShowCancelBtn: true,
        cancelBtnText: 'Cancel',
        cancelBtn: {
            event: closeModal
        },
        closeEvent: () => {},
        beforeShowEvent: () => {},
        afterShowEvent: () => {},
    }
    Object.assign(defaultConfig, config)
    const modal = document.createElement('div')
    modal.className = 'modal ' + defaultConfig.class.trim()
    if(typeof defaultConfig.position.top === 'number') {
        let top = (getScroll().top + defaultConfig.position.top)
        modal.style.top = top + 'px'
    } else {
        modal.style.top = 'calc(' + defaultConfig.position.top + ' + ' + getScroll().top + 'px)'
    }
    if(defaultConfig.width) {
        modal.style.width = defaultConfig.width + 'px'
    }
    modal.setAttribute('aria-hidden', true)
    // header
    if(defaultConfig.showHeader) {
        const header = document.createElement('div')
        header.className = 'modal-header'
        const closeIcon = document.createElement('i')
        closeIcon.className = 'iconfont iconbuzhichi'
        closeIcon.addEventListener('click', () => {
            defaultConfig.closeEvent()
            closeModal()
        })
        if(defaultConfig.title) {
            const title = document.createElement('div')
            title.className = 'title'
            title.innerText = defaultConfig.title
            header.appendChild(title)
        }
        header.appendChild(closeIcon)
        modal.appendChild(header)
    }
    // body
    const body = document.createElement('div')
    body.className = 'modal-body'
    body.innerHTML = defaultConfig.content
    modal.appendChild(body)
    // footer
    if(defaultConfig.isShowConfirmBtn || defaultConfig.isShowCancelBtn) {
        const footer = document.createElement('div')
        footer.className = 'modal-footer'
        if(defaultConfig.isShowConfirmBtn) {
            const confirmBtn = document.createElement('button')
            confirmBtn.className = 'gd-btn btn-info'
            confirmBtn.innerText = defaultConfig.confirmBtnText
            confirmBtn.addEventListener('click', defaultConfig.confirmBtn.event)
            footer.appendChild(confirmBtn)
        }
        if(defaultConfig.isShowCancelBtn) {
            const cancelBtn = document.createElement('button')
            cancelBtn.className = 'gd-btn btn-default'
            cancelBtn.innerText = defaultConfig.cancelBtnText
            cancelBtn.addEventListener('click', defaultConfig.cancelBtn.event)
            footer.appendChild(cancelBtn)
        }
        modal.appendChild(footer)
    }
    defaultConfig.beforeShowEvent(modal)
    document.body.appendChild(modal)
    showMask({
        zIndex: 450,
        event: () => {
            defaultConfig.closeEvent()
            closeModal()
        }
    })
    defaultConfig.afterShowEvent()
}
function closeModal () {
    const modal = document.querySelector('.modal')
    if(modal) {
        modal.remove()
    }
    hideMask()
}
function showNoData(el, minHeight) {
    let e = document.createElement('div')
    e.className = 'no-data'
    let img = document.createElement('i')
    img.className = 'iconfont iconkongshuju2'
    e.appendChild(img)
    let tx = document.createElement('div')
    tx.innerText = 'No related data available'
    e.appendChild(tx)
    el.appendChild(e)
    if(minHeight) {
        el.parentNode.style.minHeight = minHeight + 'px'
    }
}
function showNoDataImg(el, config = {}) {
    let wrap = '<div class="no-data">'
    if(config.imgSize) {
        wrap +='<img width="' + config.imgSize + '" height="' + config.imgSize + '" src="/static/img/ins/noData.png" ' +
            'alt="no data img" srcset="/static/img/ins/noData@2x.png 2x, /static/img/ins/noData@3x.png 3x">'
    } else {
        wrap +='<img width="131" height="131" src="/static/img/ins/noData.png" ' +
            'alt="no data img" srcset="/static/img/ins/noData@2x.png 2x, /static/img/ins/noData@3x.png 3x">'
    }
    if(config.title) {
        wrap += '<div class="title">' + config.title + '</div>'
    } else {
        wrap += '<div class="title">No related data available</div>'
    }
    wrap += '</div>'
    if(config.isECharts) {
        el.removeAttribute('_echarts_instance_')
    }
    if(config.isTable) {
        let tableWrap = '<tr>' +
            '<td colSpan="' + (config.tableColSpan || 7) + '">' +
            wrap +
            '</td>' +
            '</tr>'
        el.innerHTML = tableWrap
    } else {
        el.innerHTML = wrap
    }
}
function showLock(el, config = {}) {
    let lock = document.createElement('div')
    lock.className = 'lock'
    let innerEl = document.createElement('div')
    innerEl.className = 'lock-wrap'
    if(config.inner) {
        innerEl.innerHTML = config.inner
    } else {
        let inner = '<div class="title"> Only available for '
        if(config.roleId === 3) {
            inner += 'ADVANCED'
        } else if(config.roleId === 4) {
            inner += 'PRO'
        }
        inner += ' version users or higher, ' +
            '<a href="' + (config.updateUrl || '/pricing') + '">upgrade now!</a>' +
            '</div>'
        innerEl.innerHTML = inner
    }
    let iconEl = document.createElement('i')
    iconEl.className = 'iconfont iconsuoding'
    lock.appendChild(innerEl)
    lock.appendChild(iconEl)
    el.appendChild(lock)
}
function showTips(e) {
    e.children[0].show()
}
function hideTips(e) {
    e.children[0].hide()
}
function getEncodeUrl(url, data = {}) {
    let json = JSON.stringify(data).replace(/&/g,'%26').replace(/\+/g,'%2B').replace(/\s/g,'%20').replace(/#/g,'%23')
    return encodeURI(url + '?data=' + json)
}
function checkEmail(str) {
    let reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/
    return reg.test(str)
}
function throttle(func, delay = 500) {
    let firstTime = 0
    return function() {
        const curTime = Date.now()
        if(curTime - firstTime > delay) {
            func.apply(this, [...arguments])
            firstTime = Date.now()
        }
    }
}
function debounce(func, delay = 500) {
    let timer = null
    return function (){
        if(timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            func.apply(this, [...arguments])
        }, delay)
    }
}

function getElementPosition(element) {
    let actualLeft = element.offsetLeft
    let actualTop = element.offsetTop
    let current = element.offsetParent

    while (current !== null) {
        actualLeft += current.offsetLeft
        actualTop += current.offsetTop
        current = current.offsetParent
    }

    return {
        left: actualLeft,
        top: actualTop
    }
}

function hex2int(hex) {
    let len = hex.length, a = new Array(len), code
    for (let i = 0; i < len; i++) {
        code = hex.charCodeAt(i)
        if (48<=code && code < 58) {
            code -= 48
        } else {
            code = (code & 0xdf) - 65 + 10
        }
        a[i] = code
    }

    return a.reduce(function(acc, c) {
        acc = 16 * acc + c
        return acc
    }, 0)
}
function getQueryByUrl (key, url = location.href){
    const reg = new RegExp('[?|&]' + key + '=([^&]*)')

    const matches = url.match(reg)
    if (matches && matches[1]) {
        return matches[1]
    }
}

/**
 *
 * @param url
 * @param type 0.blogger 1.media 2.product
 * @param size 0.small 1.middle 2.large
 */
function getImage(url, type, size) {
    if(!url) {
        return defaultImage[type][size]
    }
    const xTime = getQueryByUrl('oe', url)
    if(xTime) {
        const expireTime = (hex2int(xTime) - 3600)* 1e3
        const currentTime = new Date().getTime()
        if(currentTime >= expireTime) {
            url = defaultImage[type][size]
        }
    }
    return url
}
function getNumber(number) {
    const num = +number
    return num? numFormat(+num) : '-'
}
const gugeeOS = function() {
    let ua = navigator.userAgent,
        isWindowsPhone = /(?:Windows Phone)/.test(ua),
        isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
        isAndroid = /(?:Android)/.test(ua),
        isFireFox = /(?:Firefox)/.test(ua),
        isHuawei = /(?:Huawei)/.test(ua),
        isChrome = /(?:Chrome|CriOS)/.test(ua),
        isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
        isIPhone = /(?:iPhone)/.test(ua) && !isTablet,
        isPc = !isIPhone && !isAndroid && !isSymbian;
    return {
        isTablet: isTablet,
        isIPhone: isIPhone,
        isAndroid: isAndroid,
        isHuawei: isHuawei,
        isPc: isPc
    }
}()
